package org.wesc.boot.webapi.api.system;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.wesc.boot.common.api.R;
import org.wesc.boot.dao.domain.QueryRequest;
import org.wesc.boot.dao.entity.SysLog;
import org.wesc.boot.service.system.log.SysLogAdvanceService;
import org.wesc.boot.webapi.base.BaseApi;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author Wesley
 * @date 2021/4/29
 */
@Api(tags={"系统日志接口"})
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/syslog")
public class LogApi extends BaseApi {

    private final SysLogAdvanceService sysLogAdvanceService;

    @GetMapping("list")
    public R<Map<String, Object>> logList(SysLog log, QueryRequest request) {
        return R.data(getDataTable(this.sysLogAdvanceService.findLogs(log, request)));
    }

    @DeleteMapping("/{ids}")
    public R<String> deleteLogs(@NotBlank(message = "{required}") @PathVariable String ids) {
        try {
            String[] logIds = ids.split(StringPool.COMMA);
            this.sysLogAdvanceService.deleteLogs(logIds);
            return R.success();
        } catch (Exception e) {
            String message = "删除日志失败";
            log.error(message, e);
            return R.fail(message);
        }
    }

    @PostMapping("excel/export")
    public void exportExcel(QueryRequest request, SysLog log, HttpServletResponse response) throws IOException {
        response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");
        String sheetName = "系统日志列表";
        List<SysLog> logList = this.sysLogAdvanceService.findLogs(log, request).getRecords();
        EasyExcel.write(response.getOutputStream(), SysLog.class).sheet(sheetName).doWrite(logList);
    }
}
